<template>
  <view class="leader-index-container">
    <view class="head px-2 box-border">
      <!-- 用户信息 -->
      <template v-if="userInfoStore.token">
        <view class="user flex flex-row justify-between items-center py-4">
          <userOfTopLeft
            :userAvatar="userInfoStore.userInfo.avatar"
            :userName="userInfoStore.userInfo.userName"
            @onUserInfo="onPageJump('/subPages/leader/mine/index')"
          ></userOfTopLeft>
        </view>
      </template>

      <!-- 未登录 -->
      <template v-else>
        <view class="user flex flex-row justify-start items-center py-4">
          <userOfTopLeft
            userAvatar=""
            userName="未登录"
            :showMoreIcon="false"
            @onUserInfo="onPageJump('/pages/register/register')"
          ></userOfTopLeft>
        </view>
      </template>

      <!-- 轮播图 -->
      <view class="swiper">
        <up-swiper
          :list="swipers"
          circular
          @change="(e: any) => (current = e.current)"
          height="360rpx"
          radius="16rpx"
        >
          <template #indicator>
            <view class="indicator">
              <view
                class="indicator__dot"
                v-for="(item, index) in swipers"
                :key="index"
                :class="[index === current && 'indicator__dot--active']"
              >
              </view>
            </view>
          </template>
        </up-swiper>
      </view>
    </view>
    <view class="content px-2 box-border">
      <!-- 社区民警状态 -->
      <moduleOuterBox
        moduleTitle="社区民警状态"
        :moduleIcon="sqmjztIcon"
        @scanModuleDeatil="onPageJump('/subPages/leader/policeStatus/index')"
      >
        <view class="">
          <up-grid :border="false" align="center" col="2">
            <up-grid-item
              v-for="(item, index) in policeStatusCount"
              :key="index"
            >
              <text class="text-[#4AABFF] text-[42rpx]">{{ item.num }}</text>
              <text class="text-black text-[26rpx] pt-3.25">{{
                item.title
              }}</text>
            </up-grid-item>
          </up-grid>
        </view>
      </moduleOuterBox>
      <!-- 服务评价统计 -->
      <moduleOuterBox
        moduleTitle="服务评价统计"
        :moduleIcon="fwpjtjIcon"
        showQuery
        :modeType="evaluationType"
        @scanModuleDeatil="
          onPageJump('/subPages/leader/serviceEvaluation/index')
        "
        @changeMode="updateEvaluationStat"
      >
        <view class="evaluation-charts">
          <qiun-data-charts
            type="ring"
            :opts="
              evaluationType === 0
                ? evaluationChartMonth.opts
                : evaluationChartYear.opts
            "
            :chartData="
              evaluationType === 0
                ? evaluationChartMonth.chartData
                : evaluationChartYear.chartData
            "
          />
        </view>
      </moduleOuterBox>
      <!-- 举报投诉统计 -->
      <moduleOuterBox
        moduleTitle="举报投诉统计"
        :moduleIcon="jbtstjIcon"
        showQuery
        :modeType="complaintType"
        showTotal
        :totalNum="
          complaintType === 0 ? complaintMonth.total : complaintYear.total
        "
        @scanModuleDeatil="onPageJump('/subPages/leader/reportComplaint/index')"
        @changeMode="updatecomplaintStat"
      >
        <view class="complaint-charts">
          <qiun-data-charts
            type="column"
            :opts="complaintChartOpts"
            tooltipFormat="normalTooltip"
            :chartData="
              complaintType === 0
                ? complaintMonth.chartData
                : complaintYear.chartData
            "
          />
          <!-- :ontouch="true" -->
        </view>
      </moduleOuterBox>
      <!-- 其他数据统计 -->
      <moduleOuterBox moduleTitle="其他数据统计" :moduleIcon="qtsjtjIcon">
        <view class="">
          <up-grid :border="false" align="center" gap="18rpx">
            <up-grid-item v-for="(item, index) in otherDataStat" :key="index">
              <view
                class="flex flex-col item-center text-center w-[100%] h-[100%] part-box py-2 box-border"
                :style="`background: linear-gradient(180deg, ${item.bgColor0} 0%, ${item.bgColor1} 100%);`"
              >
                <text
                  class="text-[42rpx] font-bold"
                  :style="`color:${item.color};`"
                  >{{ item.num }}</text
                >
                <text class="text-[29rpx] text-black pt-1">{{
                  item.title
                }}</text>
              </view>
            </up-grid-item>
          </up-grid>
        </view>
      </moduleOuterBox>
      <up-gap height="16"></up-gap>
      <up-toast ref="uToastRef"></up-toast>
    </view>
  </view>
</template>

<script setup lang="ts">
import moduleOuterBox from "@/components/moduleOuterBox/moduleOuterBox.vue";
import sqmjztIcon from "@/static/icon/sqmjzt.png";
import fwpjtjIcon from "@/static/icon/fwpjtj.png";
import jbtstjIcon from "@/static/icon/jbtstj.png";
import qtsjtjIcon from "@/static/icon/qtsjtj.png";
import { evaluationStat } from "@/api/evaluation/index";
import { policeStatusStat } from "@/api/police/index";
import { complaintStat } from "@/api/complaint/index";
import { onPageJump, toFixedWithoutTrailingZeros } from "@/utils/tools";
import dayjs from "dayjs";
import { useUserInfoStore } from "@/stores/userInfo";
const userInfoStore = useUserInfoStore();

const uToastRef = <any>ref(null);
const current = ref(0);
const swipers = reactive([
  "https://mscy.cqlandun.com:8088/static/police-banner1.png",
  "https://mscy.cqlandun.com:8088/static/police-banner2.png",
  "https://mscy.cqlandun.com:8088/static/police-banner3.png",
]);

const data = reactive({
  policeStatusCount: [
    {
      num: 0,
      title: "今日在岗",
    },
    {
      num: 0,
      title: "今日不在岗",
    },
  ],
  evaluationType: 0,
  complaintType: 0,
  params: {
    policeLeaderId: userInfoStore.userInfo.userId,
    communityId: null,
  },
  complaintMonth: {
    total: 0,
    chartData: {},
  },
  complaintYear: {
    total: 0,
    chartData: {},
  },
  otherDataStat: [
    {
      num: 0,
      title: "办事咨询",
      color: "#F2AD32",
      bgColor0: "#FEF9EC",
      bgColor1: "#FFFCF7",
    },
    {
      num: 0,
      title: "注册用户量",
      color: "#F4806C",
      bgColor0: "#F9FEFD",
      bgColor1: "#F3FFFB",
    },
    {
      num: 0,
      title: "办理点击量",
      color: "#459BFD",
      bgColor0: "#F3F9FE",
      bgColor1: "#EEF6FC",
    },
    {
      num: 0,
      title: "隐患随手拍",
      color: "#32C4F2",
      bgColor0: "#EBFFFD",
      bgColor1: "#EBFFFD",
    },
    {
      num: 0,
      title: "预约服务",
      color: "#FF5D6D",
      bgColor0: "#FFEBEB",
      bgColor1: "#FFEBEB",
    },
  ],
});
const {
  policeStatusCount,
  evaluationType,
  complaintType,
  params,
  complaintMonth,
  complaintYear,
  otherDataStat,
} = toRefs(data);
const evaluationChartMonth = reactive({
  chartData: {},
  opts: {
    animation: false, // 关闭动画
    update: true, // 关键：是否开启连续更新数据的方法,开启之后就不会抖动了
    duration: 0, // 关闭动画过度
    rotate: false,
    rotateLock: false,
    color: ["#39FB00", "#4AABFF", "#F55300"],
    padding: [10, 10, 10, 10],
    dataLabel: true,
    enableScroll: false,
    legend: {
      show: false,
    },
    title: {},
    subtitle: {
      name: "",
    },
    extra: {
      ring: {
        ringWidth: 20, //圆环的宽度
        centerColor: "#ffffff", //中间填充圆形的颜色
        activeOpacity: 0.5, //启用Tooltip点击时，突出部分的透明度
        activeRadius: 8, //启用Tooltip点击时，突出部分的宽度
        offsetAngle: 0, //起始角度偏移度数，顺时针方向，
        labelWidth: 15, //数据标签到饼图外圆连线的长度
        border: false, //是否绘制各类别中间的分割线
      },
    },
  },
});
const evaluationChartYear = reactive({
  chartData: {},
  opts: {
    animation: false, // 关闭动画
    update: true, // 关键：是否开启连续更新数据的方法,开启之后就不会抖动了
    duration: 0, // 关闭动画过度
    rotate: false,
    rotateLock: false,
    color: ["#39FB00", "#4AABFF", "#F55300"],
    padding: [10, 10, 10, 10],
    dataLabel: true,
    enableScroll: false,
    legend: {
      show: false,
    },
    title: {},
    subtitle: {
      name: "",
    },
    extra: {
      ring: {
        ringWidth: 20, //圆环的宽度
        centerColor: "#ffffff", //中间填充圆形的颜色
        activeOpacity: 0.5, //启用Tooltip点击时，突出部分的透明度
        activeRadius: 8, //启用Tooltip点击时，突出部分的宽度
        offsetAngle: 0, //起始角度偏移度数，顺时针方向，
        labelWidth: 15, //数据标签到饼图外圆连线的长度
        border: false, //是否绘制各类别中间的分割线
      },
    },
  },
});
const complaintChartOpts = ref({
  animation: false, // 关闭动画
  update: true, // 关键：是否开启连续更新数据的方法,开启之后就不会抖动了
  duration: 0, // 关闭动画过度
  padding: [10, 5, 5, 0],
  enableScroll: false, //true,
  legend: { show: false },
  dataLabel: false, // 不显示数据标签
  xAxis: {
    rotateLabel: true, // 启用旋转功能减少横向空间占
    rotateAngle: 45, // 文字旋转的角度，取值范围(-90至90)
    // scrollShow: true,
    // itemCount: 8,
    interval: 0,
    boundaryGap: 'justify', // 让柱状图两端不留空白
    disableGrid: true, //不绘制纵向网格
    fontColor: "#000000", //字体颜色
    fontSize: 10, //字体大小
    axisLineColor: "#707070", //坐标轴轴线颜色
    marginTop: "5", //X轴文字距离轴线的距离
    // labelCount: 6, //数据点文字单屏幕限制显示的数量
    formatter: function (value, index, opts) {
      // const poi = value.indexOf("社");
      // if (poi > -1) {
      //   // 在字符前面插入换行符
      //   value = value.substring(0, poi) + "<br/>" + value.substring(poi);
      // }
      // console.log(value);
      return value;
    },
  },
  yAxis: {
    disableGrid: true, //不绘制横向向网格
    data: [
      {
        min: 0,
        calibration: true, //刻度线是否显示
        fontColor: "#8A8A8A", //字体颜色
        fontSize: 12, //字体大小
        axisLineColor: "#707070", //坐标轴轴线颜色
      },
    ],
  },
  extra: {
    column: {
      type: "group",
      width: 10,
      linearType: "custom", //渐变类型
      customColor: ["#88C5EC", "#4299FE"],
      activeBgColor: "#000000", //当前点击柱状图的背景颜色
      activeBgOpacity: 0.08, //当前点击柱状图的背景颜色透明度
    },
  },
});

// 民警状态及其他数据统计
const getStatusStat = () => {
  policeStatusStat()
    .then((res: any) => {
      const { data } = res;
      policeStatusCount.value[0].num = data.dutyCount; //在岗
      policeStatusCount.value[1].num = data.noDutyCount; //不在岗
      otherDataStat.value[0].num = data.consultCount; //办事咨询
      otherDataStat.value[1].num = data.registerUserCount; //注册用户量
      otherDataStat.value[2].num = data.handleClickCount; //办理点击量
      otherDataStat.value[3].num = data.snapshotCount; //办理点击量
      otherDataStat.value[4].num = data.reservationCount; //办理点击量
    })
    .catch((err: any) => {
      uToastRef.value.show({
        type: "error",
        message: err,
      });
    });
};
// 举报投诉统计改变筛选条件
const updatecomplaintStat = (mode: number) => {
  complaintType.value = mode;
};
// 举报投诉统计
const getComplaintStat = (type: any) => {
  let param = {};
  if (type === 0) {
    param = {
      ...params.value,
      ...{
        type,
        yearMonth: dayjs(new Date()).format("YYYY-MM"),
      },
    };
  } else {
    param = {
      ...params.value,
      ...{
        type,
        yearMonth: dayjs(new Date()).format("YYYY"),
      },
    };
  }
  complaintStat(param)
    .then((res: any) => {
      const { data } = res;
      data.cltCmyChartVos = data.cltCmyChartVos ?? [];
      let xdata = <any>[];
      let ydata = <any>[];
      if (data.cltCmyChartVos.length) {
        data.cltCmyChartVos.forEach((item: any) => {
          xdata.push(item.communityName);
          ydata.push(+item.communityCount);
          if (type === 0) {
            complaintMonth.value.total += +item.communityCount;
          } else {
            complaintYear.value.total += +item.communityCount;
          }
        });
      }
      let seriesData = {
        categories: xdata,
        series: [
          {
            name: "投诉次数",
            data: ydata,
          },
        ],
      };
      if (type === 0) {
        complaintMonth.value.chartData = JSON.parse(JSON.stringify(seriesData));
      } else {
        complaintYear.value.chartData = JSON.parse(JSON.stringify(seriesData));
      }
    })
    .catch((err: any) => {
      uToastRef.value.show({
        type: "error",
        message: err,
      });
    });
};
// 服务评价统计改变筛选条件
const updateEvaluationStat = (mode: number) => {
  evaluationType.value = mode;
};
// 服务评价统计
const getEvaluationStat = (type: any) => {
  let seriesData = {
    series: [
      {
        data: [
          {
            name: "满意",
            value: 0,
            labelText: `满意：0%`,
          },
          {
            name: "一般",
            value: 0,
            labelText: `一般：0%`,
          },
          {
            name: "不满意",
            value: 0,
            labelText: `不满意：0%`,
          },
        ],
      },
    ],
  };
  let title = {
    name: 0,
    fontSize: 25,
    color: "#000000",
  };
  let param = {};
  if (type === 0) {
    param = {
      ...params.value,
      ...{
        type,
        yearMonth: dayjs(new Date()).format("YYYY-MM"),
      },
    };
  } else {
    param = {
      ...params.value,
      ...{
        type,
        yearMonth: dayjs(new Date()).format("YYYY"),
      },
    };
  }
  evaluationStat(param)
    .then((res: any) => {
      const { data } = res;
      if (data.sumCount > 0) {
        seriesData.series[0].data[0].value = +data.satisfiedCount;
        seriesData.series[0].data[0].labelText = `满意：${toFixedWithoutTrailingZeros(
          (data.satisfiedCount / +data.sumCount) * 100
        )}%`;
        seriesData.series[0].data[1].value = +data.generalCount;
        seriesData.series[0].data[1].labelText = `一般：${toFixedWithoutTrailingZeros(
          (data.generalCount / +data.sumCount) * 100
        )}%`;
        seriesData.series[0].data[2].value = +data.dissatisfiedCount;
        seriesData.series[0].data[2].labelText = `不满意：${toFixedWithoutTrailingZeros(
          (data.dissatisfiedCount / +data.sumCount) * 100
        )}%`;
        title.name = +data.sumCount;
      }
      if (type === 0) {
        evaluationChartMonth.chartData = JSON.parse(JSON.stringify(seriesData));
        evaluationChartMonth.opts.title = JSON.parse(JSON.stringify(title));
      } else {
        evaluationChartYear.chartData = JSON.parse(JSON.stringify(seriesData));
        evaluationChartYear.opts.title = JSON.parse(JSON.stringify(title));
      }
    })
    .catch((err: any) => {
      uToastRef.value.show({
        type: "error",
        message: err,
      });
    });
};

// 初始化数据
const initData = () => {
  getStatusStat();
  getEvaluationStat(0);
  getEvaluationStat(1);
  getComplaintStat(0);
  getComplaintStat(1);
};

onMounted(() => {
  initData();
});

onShow(() => {
  uni.hideHomeButton();
});

onShareAppMessage((res) => {
  return {
    title: "码上朝阳",
    path: "/pages/crowd/home/index",
    imageUrl: "/static/logo.png",
    content: "我的码上朝阳小程序",
    mpId: "wxbaec7c3e7b23e9c4",
    type: 0,
  };
});
</script>

<style lang="scss" scoped>
.leader-index-container {
  .head {
    background: linear-gradient(180deg, #0088fe 0%, #f4f5f9 100%);
  }
  .user {
    width: 100%;
    .right {
      width: 20%;
    }
  }
  .indicator {
    @include flex(row);
    justify-content: center;

    &__dot {
      height: 14rpx;
      width: 14rpx;
      border-radius: 100px;
      background-color: #eee;
      margin: 0 5px;
      transition: background-color 0.3s;

      &--active {
        background-color: #098cfe;
      }
    }
  }
  .swiper ::v-deep .u-swiper__wrapper__item__wrapper__title {
    background-color: transparent !important;
  }
  .evaluation-charts {
    width: 100%;
    height: 300rpx;
  }
  .complaint-charts {
    width: 100%;
    height: 360rpx;
  }
}
</style>
